<script setup lang="ts">
import { computed, h, ref } from 'vue';
import { NImage } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import type { GoodsImageProps } from './types';

const props = withDefaults(defineProps<GoodsImageProps>(), {
  size: 32,
  enablePreview: true,
  fallbackImage: '/images/no-image.png',
  goodKey: 'objectId'
});

const loading = ref(false);

// 计算图片URL
const imageUrl = computed(() => {
  return props.good?.goodsIcon || props.fallbackImage;
});

// 处理图片点击事件 - 获取商品多图进行预览
const handleImageClick = async (event: Event) => {
  if (!props.enablePreview || loading.value) return;

  event.stopPropagation();

  const goodId = props.good?.[props.goodKey] || props.good?.goodId;
  if (!goodId) {
    window.$message?.warning('无法获取商品ID');
    return;
  }

  loading.value = true;

  // 显示加载提示
  const loadingMessage = window.$message?.loading('正在加载商品图片...', {
    duration: 0
  });

  // 调用API获取商品多图
  const response = await InventoryGoods.getSubGoodIcons(goodId);

  // 关闭加载提示
  loadingMessage?.destroy();
  loading.value = false;

  if (response && !response.error && response.data) {
    const images = Array.isArray(response.data) ? response.data : [response.data];

    if (images.length > 0) {
      // 使用Naive UI的图片预览功能
      // 创建一个临时的图片组来实现多图预览
      const previewImages = images.filter(img => img && img.trim() !== '');

      if (previewImages.length > 1) {
        // 多图预览：创建预览模态框
        window.$dialog?.info({
          title: `商品图片 (${previewImages.length}张)`,
          content: () =>
            h(
              'div',
              { class: 'grid grid-cols-3 gap-2' },
              previewImages.map(src =>
                h(NImage, {
                  src,
                  width: 120,
                  height: 120,
                  previewSrc: src,
                  class: 'rounded border'
                })
              )
            ),
          positiveText: '关闭'
        });
      } else {
        // 单图预览：直接使用NImage的预览功能
        window.$message?.success('点击图片可查看大图');
      }
    } else {
      window.$message?.info('该商品暂无更多图片');
    }
  } else {
    window.$message?.error('获取商品图片失败');
  }
};
</script>

<template>
  <div class="flex justify-center">
    <NImage
      :src="imageUrl"
      :width="size"
      :height="size"
      :preview-src="imageUrl"
      :fallback-src="fallbackImage"
      class="cursor-pointer border border-gray-200 rounded-3px"
      @click="handleImageClick"
    />
  </div>
</template>
